package com.netforce.util.launch;

import java.io.File;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.resource.FileResource;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

public class JettyLauncher
{
  static public void main(String[] theArguments)
  {
    JettyLauncher starter = new JettyLauncher();
    try
    {
      starter.launch(theArguments);
    }
    catch (Exception anException)
    {
      anException.printStackTrace();
    }
  }

  public void launch(String[] theArguments) throws Exception
  {
    readArguments(theArguments);
    start();
  }

  protected void readArguments(String[] theArguments) throws Exception
  {
    CmdLineParser parser = new CmdLineParser(this);
    parser.parseArgument(theArguments);
  }

  protected void start() throws Exception
  {
    Server server = buildServer(port);
    server.setHandler(buildWebAppContext(new File(webApp)));

    server.start();
    server.join();
  }

  protected Server buildServer(int aPort)
  {
    Server server = new Server();
    ServerConnector serverConnector = new ServerConnector(server);
    serverConnector.setPort(aPort);
    server.setConnectors(new Connector[]
      {
        serverConnector
      });
    return server;
  }

  protected WebAppContext buildWebAppContext(File aBase)
  {
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/");
    webAppContext.setResourceBase(aBase.getPath());
    webAppContext.setConfigurations(new Configuration[]
      {
        new WebXmlConfiguration(),
        new AnnotationConfiguration()
      });
    // if it is not a packaged war
    if (aBase.isDirectory())
    {
      loadExternalResources(webAppContext);
    }
    return webAppContext;
  }

  protected void loadExternalResources(WebAppContext aWebAppContext)
  {
    String classPath = System.getProperty("java.class.path");
    String[] classPathEntries = classPath.split(File.pathSeparator);
    for (String classPathEntry : classPathEntries)
    {
      aWebAppContext.getMetaData().addContainerResource(new FileResource(new File(classPathEntry).toURI()));
    }
  }

  @Option(name = "-port")
  protected int port;
  @Option(name = "-webapp")
  protected String webApp;
}
